#include <iostream>
using namespace std;
#include <sys/types.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <error.h>

int main()
{
    int money = 10000;

    /* 创建子进程 */
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error:");
        exit(-1);
    }
    else if (pid == 0)
    {
        sleep(3);
        /* 子进程 */
        cout << "l am child process" << endl;
        cout << "child money:" << money << endl;

        /* 打开文件 */
        int fd = open("./test.txt", O_RDONLY);
        if (fd == -1)
        {
            /* 打印错误原因 */
            perror("open error:");
            exit(-1);
        }
        int assert = 0;
        read(fd, &assert, sizeof(assert));

        close(fd);

        cout << "assert:" << assert << endl;
    }
    else
    {
        /* 父进程 */
        /* 程序走这边:说明pid > 0 */
        cout << "l am parent process" << endl;

        money += 5000000;
        cout << "parent money:" << money << endl;

        /* 打开文件 */
        int fd = open("./test.txt", O_RDWR | O_CREAT, 0644);
        if (fd == -1)
        {
            /* 打印错误原因 */
            perror("open error:");
            exit(-1);
        }

        /* 向文件里面写数据 */
        write(fd, &money, sizeof(money));
        cout << "fd:" << fd << endl;

        /* 关闭文件 */
        close(fd);
    }

    cout << "hello world" << endl;

    while (1)
    {
        sleep(1);
    }

    return 0;
}